/**
 * divs2slides.js
 * Ver : 1.3.2
 * update: 14/05/2018
 * Author: meshesha , https://github.com/meshesha
 * LICENSE: MIT
 * url:https://github.com/meshesha/divs2slides
 *
 * New:
 *  - fixed fullscreen (fullscreen on div only insted all page)
 */
;(function ($) {
  var orginalMainDivWidth,
    orginalMainDivHeight,
    orginalSlidesWarpperScale,
    orginalSlideTop,
    orginalSlideLeft,
    orginalSlidesToolbarWidth,
    orginalSlidesToolbarTop
  var pptxjslideObj = {
    init: function () {
      var data = pptxjslideObj.data
      var divId = data.divId
      var isInit = data.isInit
      $("#" + divId + " .slide").hide()
      if (data.slctdBgClr != false) {
        var preBgClr = $(document.body).css("background-color")
        data.prevBgColor = preBgClr
        $(document.body).css("background-color", data.slctdBgClr)
      }
      if (data.nav && !isInit) {
        data.isInit = true
        // Create navigators
        $("#" + divId).prepend(
          $("<div></div>").attr({
            class: "slides-toolbar",
            style:
              "width: 90%; padding: 10px; text-align: center;font-size:18px; color: " +
              data.navTxtColor +
              ";", ////New for Ver: 1.2.1
          }),
        )
        $("#" + divId + " .slides-toolbar").prepend(
          $("<img></img>")
            .attr({
              id: "slides-next",
              class: "slides-nav",
              alt: "Next Slide",
              src: "",
              style: "float: right;cursor: pointer;opacity: 0.7;",
            })
            .on("click", pptxjslideObj.nextSlide),
        )
        if (data.showTotalSlideNum) {
          $("#" + divId + " .slides-toolbar").prepend(
            $("<span></span>")
              .attr({
                id: "slides-total-slides-num",
              })
              .html(data.totalSlides),
          )
        }
        if (data.showSlideNum && data.showTotalSlideNum) {
          $("#" + divId + " .slides-toolbar").prepend(
            $("<span></span>")
              .attr({
                id: "slides-slides-num-separator",
              })
              .html(" / "),
          )
        }
        if (data.showSlideNum) {
          $("#" + divId + " .slides-toolbar").prepend(
            $("<span></span>")
              .attr({
                id: "slides-slide-num",
              })
              .html(data.slideCount),
          )
        }
        if (data.showFullscreenBtn) {
          $("#" + divId + " .slides-toolbar").prepend(
            $("<img></img>")
              .attr({
                id: "slides-full-screen",
                class: "slides-nav-play",
                alt: "fullscreen Slide",
                src: "",
                style:
                  "float: left;cursor: pointer;opacity: 0.7; padding: 0 10px 0 10px",
              })
              .bind("click", function () {
                pptxjslideObj.fullscreen()
              }),
          )
        }
        if (data.showPlayPauseBtn) {
          $("#" + divId + " .slides-toolbar").prepend(
            $("<img></img>")
              .attr({
                id: "slides-play-pause",
                class: "slides-nav-play",
                alt: "Play/Pause Slide",
                src: "",
                style:
                  "float: left;cursor: pointer;opacity: 0.7;  padding: 0 10px 0 10px",
              })
              .html("<span style='font-size:80%;'>&#x23ef;</span>")
              .bind("click", function () {
                if (data.isSlideMode) {
                  pptxjslideObj.startAutoSlide()
                }
              }),
          )
        }
        $("#" + divId + " .slides-toolbar").prepend(
          $("<img></img>")
            .attr({
              id: "slides-prev",
              class: "slides-nav",
              alt: "Prev. Slide",
              src: "",
              style: "float: left;cursor: pointer; opacity: 0.7;",
            })
            .bind("click", pptxjslideObj.prevSlide),
        )

        $(".slides-nav, .slides-nav-play").on("mouseover", function () {
          $(this).css({
            opacity: 1,
          })
        })
        $(".slides-nav, .slides-nav-play").on("mouseout", function () {
          $(this).css({
            opacity: 0.7,
          })
        })
        if (data.slideCount == 1) {
          $("#" + divId + " #slides-prev").hide()
        } else if (data.slideCount == data.totalSlides) {
          $("#" + divId + " #slides-next").hide()
        } else {
          $("#" + divId + " #slides-next").show()
        }
      } else {
        $("#" + divId + " .slides-toolbar").show()
        data.isEnbleNextBtn = true
        data.isEnblePrevBtn = true
      }
      if (document.getElementById("all_slides_warpper") === null) {
        $("#" + divId + " .slide").wrapAll(
          "<div id='all_slides_warpper'></div>",
        )
      }
      // Go to first slide
      pptxjslideObj.gotoSlide(1)
    },
    nextSlide: function () {
      var data = pptxjslideObj.data
      var isLoop = data.isLoop
      var isAutoMode = data.isAutoSlideMode
      if (data.slideCount < data.totalSlides) {
        pptxjslideObj.gotoSlide(data.slideCount + 1)
        if (!isAutoMode) $("#slides-next").show()
      } else {
        if (isLoop) {
          pptxjslideObj.gotoSlide(1)
        } else {
          if (!isAutoMode) $("#slides-next").hide()
        }
      }
      if (!isAutoMode) {
        if (data.slideCount > 1) {
          $("#slides-prev").show()
        } else {
          $("#slides-prev").hide()
        }
        if (data.slideCount == data.totalSlides && !isLoop) {
          $("#slides-next").hide()
        }
      }
      //return this;
    },
    prevSlide: function () {
      var data = pptxjslideObj.data
      var isAutoMode = data.isAutoSlideMode
      if (data.slideCount > 1) {
        pptxjslideObj.gotoSlide(data.slideCount - 1)
      }
      if (!isAutoMode) {
        if (data.slideCount == 1) {
          $("#slides-prev").hide()
        } else {
          $("#slides-prev").show()
        }
        $("#slides-next").show()
      }
      return this
    },
    gotoSlide: function (idx) {
      var index = idx - 1
      var data = pptxjslideObj.data
      var slides = data.slides
      var prevSlidNum = data.prevSlide
      var transType = data.transition /*"slid","fade","default" */
      if (transType == "random") {
        var tType = ["", "default", "fade", "slid"]
        var randomNum = Math.floor(Math.random() * 3) + 1 //random number between 1 to 3
        transType = tType[randomNum]
      }
      var transTime = 1000 * data.transitionTime
      if (slides[index]) {
        var nextSlide = $(slides[index])
        if ($(slides[prevSlidNum]).is(":visible")) {
          //remove "index >= 1 &&" bugFix to ver. 1.2.1
          if (transType == "default") {
            $(slides[prevSlidNum]).hide(transTime)
          } else if (transType == "fade") {
            $(slides[prevSlidNum]).fadeOut(transTime)
          } else if (transType == "slid") {
            $(slides[prevSlidNum]).slideUp(transTime)
          }
        }
        if (transType == "default") {
          nextSlide.show(transTime)
        } else if (transType == "fade") {
          nextSlide.fadeIn(transTime)
        } else if (transType == "slid") {
          nextSlide.slideDown(transTime)
        }
        data.prevSlide = index
        pptxjslideObj.data.slideCount = idx
        $("#slides-slide-num").html(idx)
      }
      return this
    },
    keyDown: function (event) {
      event.preventDefault()
      var key = event.keyCode
      //console.log(key);
      var data = pptxjslideObj.data
      switch (key) {
        case 37: // Left arrow
        case 8: // Backspace
          if (data.isSlideMode && data.isEnblePrevBtn) {
            pptxjslideObj.prevSlide()
          }
          break
        case 39: // Right arrow
        case 32: // Space
        case 13: // Enter
          if (data.isSlideMode && data.isEnbleNextBtn) {
            pptxjslideObj.nextSlide()
          }
          break
        case 46: //Delete
          //if in auto mode , stop auto mode TODO
          if (data.isSlideMode) {
            var div_id = data.divId
            $("#" + div_id + " .slide").hide()
            pptxjslideObj.gotoSlide(1) //bugFix to ver. 1.2.1
          }
          break
        case 27: //Esc
          if (data.isSlideMode) {
            pptxjslideObj.closeSileMode()
            data.isSlideMode = false
          }
          break
        case 116: //F5
          if (!data.isSlideMode) {
            pptxjslideObj.startSlideMode()
            data.isSlideMode = true
            if (data.isAutoSlideMode || data.isLoopMode) {
              clearInterval(data.loopIntrval)
              data.isAutoSlideMode = false
              data.isLoopMode = false
            }
          }
          break
        case 113: // F2
          if (data.isSlideMode) {
            pptxjslideObj.fullscreen()
          }
          break
        case 119: // F8
          if (data.isSlideMode) {
            pptxjslideObj.startAutoSlide()
            //TODO : ADD indication that it is in auto slide mode
          }
          break
      }
      return true
    },
    startSlideMode: function () {
      pptxjslideObj.init()
    },
    closeSileMode: function () {
      var data = pptxjslideObj.data
      data.isSlideMode = false
      var div_id = data.divId
      $("#" + div_id + " .slides-toolbar").hide()
      $("#" + div_id + " .slide").show()
      $(document.body).css("background-color", pptxjslideObj.data.prevBgColor)
      if (data.isLoopMode) {
        clearInterval(data.loopIntrval)
        data.isLoopMode = false
      }
      pptxjslideObj.exitFullscreenMod()
    },
    startAutoSlide: function () {
      var data = pptxjslideObj.data
      var isAutoSlideOption = data.timeBetweenSlides
      var isAutoSlideMode = data.isAutoSlideMode
      if (!isAutoSlideMode && isAutoSlideOption !== false) {
        data.isAutoSlideMode = true
        //var isLoopOption = data.isLoop;
        var isStrtLoop = data.isLoopMode
        //hide and disable next and prev btn
        if (data.nav) {
          var div_Id = data.divId
          $("#" + div_Id + " .slides-toolbar .slides-nav").hide()
          $("#" + div_Id + " #slides-play-pause").attr(
            "src",
            "",
          )
        }
        data.isEnbleNextBtn = false
        data.isEnblePrevBtn = false
        ///////////////////////////////

        var t = isAutoSlideOption + data.transitionTime

        var slideNums = data.totalSlides
        var isRandomSlide = data.randomAutoSlide

        if (!isStrtLoop) {
          var timeBtweenSlides = t * 1000 //milisecons
          data.isLoopMode = true
          data.loopIntrval = setInterval(function () {
            if (isRandomSlide) {
              var randomSlideNum = Math.floor(Math.random() * slideNums) + 1
              pptxjslideObj.gotoSlide(randomSlideNum)
            } else {
              pptxjslideObj.nextSlide()
            }
          }, timeBtweenSlides)
        } else {
          clearInterval(data.loopIntrval)
          data.isLoopMode = false
        }
      } else {
        clearInterval(data.loopIntrval)
        data.isAutoSlideMode = false
        data.isLoopMode = false
        //show and enable next and prev btn
        if (data.nav) {
          var div_Id = data.divId
          $("#" + div_Id + " .slides-toolbar .slides-nav").show()
          $("#" + div_Id + " #slides-play-pause").attr(
            "src",
            "",
          )
        }
        data.isEnbleNextBtn = true
        data.isEnblePrevBtn = true
      }
    },
    fullscreen: function () {
      if (
        !document.fullscreenElement &&
        !document.mozFullScreenElement &&
        !document.webkitFullscreenElement &&
        !document.msFullscreenElement
      ) {
        // current working methods
        var data = pptxjslideObj.data
        var div_Id = data.divId
        if (document.documentElement.requestFullscreen) {
          document.getElementById(div_Id).requestFullscreen()
        } else if (document.documentElement.msRequestFullscreen) {
          document.getElementById(div_Id).msRequestFullscreen()
        } else if (document.documentElement.mozRequestFullScreen) {
          document.getElementById(div_Id).mozRequestFullScreen()
        } else if (document.documentElement.webkitRequestFullscreen) {
          document
            .getElementById(div_Id)
            .webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT)
        }
        var winWidth = $(window).width()
        var winHeight = $(window).height()
        //Need to save:
        orginalMainDivWidth = $("#" + div_Id).width()
        orginalMainDivHeight = $("#" + div_Id).height()
        var m = $("#" + div_Id + " #all_slides_warpper").css("transform")
        orginalSlidesWarpperScale = m
          .substring(m.indexOf("(") + 1, m.indexOf(")"))
          .split(",")
        orginalSlideTop = $(
          "#" + div_Id + " #all_slides_warpper .slide",
        ).offset().top
        orginalSlideLeft = $(
          "#" + div_Id + " #all_slides_warpper .slide",
        ).offset().left
        orginalSlidesToolbarWidth = $("#" + div_Id + " .slides-toolbar").width()
        orginalSlidesToolbarTop = $("#" + div_Id + " .slides-toolbar").offset()
          .top

        $("#" + div_Id).attr({
          style:
            "width: " +
            (winWidth - 10) +
            "px; height: " +
            (winHeight - 10) +
            "px;",
        })

        $("#" + div_Id + " #all_slides_warpper").css({
          transform: "scale(1)",
        })

        var slideWidth = $("#" + div_Id + " #all_slides_warpper .slide").width()
        var sildeHeight = $(
          "#" + div_Id + " #all_slides_warpper .slide",
        ).height()
        $("#" + div_Id + " #all_slides_warpper .slide").css({
          top: (winHeight - sildeHeight) / 2 + "px",
          left: (winWidth - slideWidth) / 2 + "px",
        })

        if (data.nav) {
          $("#" + div_Id + " .slides-toolbar").css({
            width: "99%",
            top: "20px",
          })
        }
        //change fullscreen icon to other icon (red color)
        $("#" + div_Id + " #slides-full-screen").attr(
          "src",
          "",
        )
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen()
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen()
        }

        pptxjslideObj.exitFullscreenMod()
      }
    },
    exitFullscreenMod: function () {
      var data = pptxjslideObj.data
      var div_Id = data.divId
      //saved:
      /*
            orginalMainDivWidth
            orginalMainDivHeight
            orginalSlidesWarpperScale
            orginalSlideTop
            orginalSlideLeft
            orginalSlidesToolbarWidth
            orginalSlidesToolbarTop
            */
      $("#" + div_Id).attr({
        style:
          "width: " +
          orginalMainDivWidth +
          "px; height: " +
          orginalMainDivHeight +
          "px;",
      })
      console.log(orginalSlidesWarpperScale[0])
      $("#" + div_Id + " #all_slides_warpper").css({
        transform: "scale(" + orginalSlidesWarpperScale[0] + ")",
      })

      $("#" + div_Id + " #all_slides_warpper .slide").css({
        top: "0px" /**orginalSlideTop +  */,
        left: "0px" /**orginalSlideLeft +  */,
      })

      if (data.nav) {
        $("#" + div_Id + " .slides-toolbar").css({
          width: orginalSlidesToolbarWidth + "px",
          top: orginalSlidesToolbarTop + "px",
        })
      }

      //change fullscreen icon to orginal icon - TODO
      $("#" + div_Id + " #slides-full-screen").attr(
        "src",
        "",
      )
    },
  }
  $.fn.divs2slides = function (options) {
    var target = $(this)
    var divId = target.attr("id")
    var slides = $("#" + divId + " .slide") //target.children();
    //console.log(slides)
    var totalSlides = slides.length
    var prevBgColor
    var settings = $.extend(
      true,
      {
        // These are the defaults.
        first: 1,
        nav: true /** true,false : show or not nav buttons*/,
        showPlayPauseBtn: true /** true,false */,
        showFullscreenBtn: true /** true,false */,
        navTxtColor: "black" /** color */,
        keyBoardShortCut: true /** true,false */,
        showSlideNum: true /** true,false */,
        showTotalSlideNum: true /** true,false */,
        autoSlide: 1 /** false or seconds (the pause time between slides) , F8 to active(condition: keyBoardShortCut: true) */,
        randomAutoSlide: false /** true,false ,(condition: autoSlide:true */,
        loop: false /** true,false */,
        background: false /** false or color*/,
        transition:
          "default" /** transition type: "slid","fade","default","random" , to show transition efects :transitionTime > 0.5 */,
        transitionTime: 1 /** transition time in seconds */,
      },
      options,
    )
    var slideCount = settings.first
    pptxjslideObj.data = {
      nav: settings.nav,
      navTxtColor: settings.navTxtColor,
      showPlayPauseBtn: settings.showPlayPauseBtn,
      showFullscreenBtn: settings.showFullscreenBtn,
      showSlideNum: settings.showSlideNum,
      showTotalSlideNum: settings.showTotalSlideNum,
      target: target,
      divId: divId,
      slides: slides,
      isSlideMode: true,
      totalSlides: totalSlides,
      slideCount: slideCount,
      prevSlide: 0,
      transition: settings.transition,
      transitionTime: settings.transitionTime,
      slctdBgClr: settings.background,
      prevBgColor: prevBgColor,
      timeBetweenSlides: settings.autoSlide,
      isLoop: settings.loop,
      isLoopMode: false,
      isAutoSlideMode: false,
      randomAutoSlide: settings.randomAutoSlide,
      isEnbleNextBtn: true,
      isEnblePrevBtn: true,
      isInit: false,
    }

    // Keyboard shortcuts
    if (settings.keyBoardShortCut) {
      $(document).bind("keydown", pptxjslideObj.keyDown)
    }
    if (document.addEventListener) {
      document.addEventListener("webkitfullscreenchange", exitHandler, false)
      document.addEventListener("mozfullscreenchange", exitHandler, false)
      document.addEventListener("fullscreenchange", exitHandler, false)
      document.addEventListener("MSFullscreenChange", exitHandler, false)
    }

    function exitHandler() {
      if (
        document.webkitIsFullScreen === false ||
        document.mozFullScreen === false ||
        document.msFullscreenElement === null
      ) {
        pptxjslideObj.exitFullscreenMod()
      }
    }
    pptxjslideObj.init()
  }
})(jQuery)
